package br.com.rapidrest.util;

import java.util.regex.Pattern;

public class RedirectUtil {

	private static final String SLASH = "/";

	private static final String DOTS = "..";

	private static final Pattern SPLIT_REGEX = Pattern.compile(SLASH);

	private static final Pattern URI_REGEX = Pattern.compile("\\.");

	public static String resolveUri(String actualUri, String targetUri) {
		actualUri = actualUri.substring(1);
		targetUri = targetUri.substring(1);

		if (actualUri.equals(targetUri)) {
			return DOTS + SLASH + actualUri;
		}

		String[] actualSplit = SPLIT_REGEX.split(actualUri);
		String[] targetSplit = SPLIT_REGEX.split(targetUri);

		int actualLength = actualSplit.length - 1;
		int targetLength = targetSplit.length - 1;

		StringBuilder relativeUri = new StringBuilder();

		if (!actualSplit[0].equals(targetSplit[0])) {
			for (int i = 0; i < actualLength; i++) {
				relativeUri.append(DOTS);
				if (i < actualLength) {
					relativeUri.append(SLASH);
				}
			}
			relativeUri.append(targetUri);
			return relativeUri.toString();
		}

		int index = 0;
		while (actualSplit[index].equals(targetSplit[index])
				&& index < actualLength && index < targetLength) {
			index++;
		}

		if (actualLength > targetLength) {
			for (int i = index; i < actualLength; i++) {
				relativeUri.append(DOTS);
				if (i <= actualLength) {
					relativeUri.append(SLASH);
				}
			}
		} else {
			for (int i = index; i < targetLength; i++) {
				relativeUri.append(targetSplit[i]);
				if (i <= targetLength) {
					relativeUri.append(SLASH);
				}
			}
		}
		relativeUri.append(targetSplit[targetLength]);

		return relativeUri.toString();
	}

	public static String getMapping(String webPackage, Class<?> clazz) {
		String mapping = clazz.getName().substring(webPackage.length());
		mapping = URI_REGEX.matcher(mapping).replaceAll("/");
		return mapping;
	}

}
